package cn.ctodb.im.server.handler;

import cn.ctodb.im.api.Command;
import cn.ctodb.im.api.Connection;
import cn.ctodb.im.dto.auth.AuthReqDTO;
import cn.ctodb.im.dto.auth.AuthRespDTO;
import cn.ctodb.im.handler.PacketHandler;
import cn.ctodb.im.proto.Auth;
import cn.ctodb.im.rpc.AuthRpc;
import cn.ctodb.im.server.peer.Peer;
import cn.ctodb.im.server.peer.PeerManager;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * All rights Reserved, Designed By www.ctodb.cn
 *
 * @version V1.0
 * @author: lichaohn@163.com
 * @Copyright: 2018 www.ctodb.cn Inc. All rights reserved.
 */
@Component
public final class AuthHandler extends PacketHandler<Auth.AuthReq> {

    @Reference(check = false)
    private AuthRpc authRpc;

    @Autowired
    private PeerManager peerManager;

    @Override
    public Command cmd() {
        return Command.AUTH_REQ;
    }

    @Override
    public void handle(Auth.AuthReq authReq, Connection connection) {
        logger.debug("接收到登录请求：{} {}", authReq.getUid(), authReq.getToken());
        AuthReqDTO authReqDTO = new AuthReqDTO();
        authReqDTO.fromProto(authReq);
        AuthRespDTO authRespDTO = authRpc.check(authReqDTO);
        logger.debug("rpc : {}", authRespDTO);
        Auth.AuthResp authResp = authRespDTO.toProto();
        connection.send(authResp);
        if (authResp.getStatus().equals(Auth.AuthResp.Status.OK)) {
            Peer peer = new Peer();
            peer.setChannel(connection.getChc().channel());
            peer.setUid(authReq.getUid());
            peer.setLoginTime(System.nanoTime());
            peer.setLastPacketTime(System.nanoTime());
            peerManager.add(peer);
            logger.debug("反馈登录成功");
        }

    }

}
